package com.mybatisPlus.servie;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mybatisPlus.Utils.JwtUtils;
import com.mybatisPlus.common.Result;
import com.mybatisPlus.dao.entity.User;
import com.mybatisPlus.dao.mapper.UserMapper;
import com.mybatisPlus.dao.service.IUserService;
import com.mybatisPlus.vo.VoUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;
/**
 * 处理用户登录注册
 * @author liHeWei
 * @since 2022-04-16
 */
@Service
public class LoginService {

    @Autowired
    private IUserService userService;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate ;

    //用户注册
    public Result register(VoUser voUser){
        User user=new User();
        if(voUser==null) return Result.fail("注册信息未填写完整");
        String salt= RandomUtil.randomString(5);
        String password = DigestUtil.md5Hex(voUser.getPassword()+salt);
        //效验账户
        QueryWrapper<User> query=new QueryWrapper<>();
        query.eq("username", voUser.getUsername())
                .or()
                .eq("email", voUser.getEmail())
                .or()
                .eq("phone_num", voUser.getPhoneNum());
        List<User> list = userService.list(query);
        if(!list.isEmpty()) return Result.fail("邮箱或用户名或手机号已被注册");
        //效验验证码,用前端传来的邮箱去redis中查询验证码
        String confirm=(String) redisTemplate.opsForValue().get(voUser.getEmail());
        if(confirm==null) return Result.fail("验证码已失效,请重新发送");
        else {
            if(!confirm.equals(voUser.getConfirm())) return Result.fail("验证码不正确");
        }
        //效验完毕,写入数据库
        user.setUsername(voUser.getUsername());
        user.setEmail(voUser.getEmail());
        user.setPhoneNum(voUser.getPhoneNum());
        user.setSalt(salt);
        user.setPassword(password);
        user.setRole("ROLE_admin");
        userService.save(user);
        return Result.succ("注册成功");
    }

    //获取用户信息
    public Result getInfo(HttpServletRequest request){
        String username=JwtUtils.getString(request.getHeader("token"), "username");
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        //保护敏感信息
        user.setPassword("****");
        return Result.succ(user);
    }

    //用户登录
    public Result login(String account,String viewPassword){
        User user;
        //判断account是邮箱还是用户名
        boolean isEmail=Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", account);
        if(isEmail){
            user=userMapper.getUserInfo(null, account);
        }else {
            user=userMapper.getUserInfo(account,null);
        }
        //验证密码
        if(user==null) return Result.fail("用户信息未注册");
        String password=DigestUtil.md5Hex(viewPassword+user.getSalt());
        if(!user.getPassword().equals(password)) return Result.fail("用户名或密码错误");
        else {
            //验证成功，生成token传回去
            HashMap<String, String> map = new HashMap<>();
            map.put("username", user.getUsername());
            String jwt = JwtUtils.getToken(map);
            return Result.succ(jwt);
        }
    }
}
